package org.example.plugins;

import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class DynamicInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String id = request.getParameter("id");
        long hash = Long.parseLong(id) % 100;
        System.out.println(hash);
        String dsKey = "master";
        /**
         * 具体在那个库里 可以 配置在db 中   比如 shard01 库：  table_00 --> table_10
         * 具体在那个库里 可以 配置在db 中   比如 shard02 库：  table_11 --> table_20
         * 根据id 可以判断具体的 库
         */
        if (0 <= hash && hash <= 50) {
            dsKey = "shard01";
        } else if (51 <= hash) {
            dsKey = "shard02";
        }
        //hash 值 指向具体的 table   table 可以用 存储过程创建
        String hashStr = StringUtils.leftPad(String.valueOf(hash), 2, '0');
        OperatorHolder.setTableExt(hashStr);
        log.info("经过多数据源filter,dsKey={},tableName:{}", dsKey,hashStr);
        //执行
        DynamicDataSourceContextHolder.push(dsKey);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        OperatorHolder.clearOperator();
        DynamicDataSourceContextHolder.poll();
    }

}
